import type { AddressType } from '@/service/type/address';
import { redirect } from 'next/navigation';
import { Select, SelectContent, SelectItem, SelectTrigger } from '../ui/select';

export default async function AddressSelector({
  searchParams,
  addresses,
  selectedAddress,
}: {
  searchParams: Record<string, string | number>;
  addresses: AddressType[];
  selectedAddress: AddressType;
}) {
  const handleSubmit = async (id: string) => {
    'use server';
    const sp = new URLSearchParams(searchParams as any);
    sp.set('addressId', id);
    redirect(`/?${sp.toString()}`);
  };

  return (
    <Select onValueChange={handleSubmit}>
      <SelectTrigger className="max-w-[400px] w-fit border-none shadow-none outline-none ring-0">
        {selectedAddress.address}
      </SelectTrigger>
      <SelectContent>
        {addresses.map((address) => (
          <SelectItem key={address.id} value={address.id.toString()}>
            <div className="space-y-1 cursor-pointer">
              <div>{address.address}</div>
              <div className="text-xs text-muted-foreground space-x-1">
                <span>{address.name}</span>
                <span>{address.phone}</span>
              </div>
            </div>
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
